package com.onlyxiahui.framework.json.validator.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.onlyxiahui.framework.json.validator.Validator;
import com.onlyxiahui.framework.json.validator.ValidatorContext;
import com.onlyxiahui.framework.json.validator.ValidatorData;
import com.onlyxiahui.framework.json.validator.ValidatorResult;
import com.onlyxiahui.framework.json.validator.error.ErrorInfoEnum;

/**
 * 
 * Date 2018-12-26 17:23:34<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class JsonEqualsToValidator implements Validator<JSONObject, Object> {

	@Override
	public String getKey() {
		return "equalsTo";
	}

	@Override
	public boolean check(Object judge) {
		return null != judge && !judge.toString().isEmpty();
	}

	@Override
	public ValidatorResult valid(ValidatorContext validatorContext, ValidatorData<JSONObject, Object> vd) {
		JSONObject data = vd.getData();
		Object attribute = vd.getAttribute();
		Object judge = vd.getJudge();
		String code = vd.getCode();
		String message = vd.getMessage();

		ValidatorResult vr = null;
		boolean mark = true;
		String name = "";
		if (null != data && null != attribute && null != judge) {
			String json = data.toJSONString();
			String judgeText = judge.toString();
			name = judgeText;
			Object value = JSONPath.read(json, name);
			mark = attribute.equals(value);
		}
		if (!mark) {
			vr = new ValidatorResult();
			vr.setErrorCode(code == null ? this.getCode() : code);
			vr.setMessage(message == null ? this.getMessage(name) : message);
			vr.setExtend(vd.getExtend());
		}
		return vr;
	}

	public String getMessage(String name) {
		StringBuilder message = new StringBuilder("与");
		message.append(name);
		message.append("不相等！");
		return message.toString();
	}

	public String getCode() {
		return ErrorInfoEnum.MATCHING_ERROR.code();
	}
}
